package jp.co.cos.ittrick.channel.controller.client;

import jp.co.cos.ittrick.channel.meta.PreModelMeta;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.model.PreModel;
import jp.co.cos.ittrick.channel.service.PageService;
import jp.co.cos.ittrick.channel.service.PreService;
import jp.co.cos.ittrick.channel.util.Utility;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

public class InsertPreController extends Controller {

    private PageService pageService;
    private PreService preService;

    public InsertPreController() {
        pageService = new PageService();
        preService = new PreService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String page = asString("page");
        String name = asString("name");
        String index = asString("index");
        String content = asString("content");

        // 親の取得
        PageModel pageModel = pageService.getPageByKey(Integer.valueOf(page));

        // Modelの設定
        PreModel model = new PreModel();
        model.setName(name);
        model.setIndex(Integer.valueOf(index));
        model.getPageModelRef().setModel(pageModel);

        Utility util = new Utility();
        content = util.htmlEscape(content);
        model.setContent(new Text(content));

        // Insert
        Key key = preService.insert(model);

        model = preService.getPreByKey((int)key.getId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(PreModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }

}
